package sample.controller.todo;

import java.util.Date;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.KeyFactory;

import sample.controller.meta.CategoryMeta;
import sample.controller.meta.TodoMeta;
import sample.controller.model.Category;
import sample.controller.model.Todo;

public class AddController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(AddController.class.getName());

    @Override
    public Navigation run() {

        CategoryMeta cm = new CategoryMeta();
        String content = asString("content");
        if (!StringUtil.isEmpty(content)) {
            Category category = null;
            String strCategoryKey = asString("category");
            if (StringUtil.isEmpty(strCategoryKey)) {
                // カテゴリが指定されてない時はblankカテゴリで登録
                category = Datastore.query(cm).filter(cm.name.equal("blank"))
                    .asSingle();
                if (category == null) {
                    category = new Category();
                    category.setName("blank");
                    Datastore.put(category);
                }
            } else {
                category = Datastore.get(cm, KeyFactory.stringToKey(strCategoryKey));
            }
            
            // Todoの保存
            Todo todo = new Todo();
            TodoMeta tm = new TodoMeta();
            // 親(Category)のキーから子のキーを生成する
            todo.setKey(Datastore.allocateId(category.getKey(), tm));
            todo.setContent(content);
            todo.setCreatedAt(new Date());
            todo.setDone(false);
            
            Datastore.put(todo);
        }
        
        requestScope("categories", Datastore.query(cm).asList());
        return forward("add.jsp");
    }
}
